/*
 * class-rename-tool
 * 扫描当前目录下所有 .zip，根据残缺信息重命名
 * gcc src/rename.c -o rename_tool.exe
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>

#define MAX_LINE 256
#define MAX_FILE 256
#define MAX_STUDENTS 200

typedef struct {
    char class_id[32];
    char id[16];
    char name[32];
} Student;

Student db[MAX_STUDENTS];
int db_size = 0;

/* 读取学生库 */
void load_students(const char* path) {
    FILE* fp = fopen(path, "r");
    if (!fp) { perror("open students.txt"); exit(EXIT_FAILURE); }
    char line[MAX_LINE];
    while (fgets(line, sizeof(line), fp) && db_size < MAX_STUDENTS) {
        if (sscanf(line, "%31s %15s %31s", db[db_size].class_id,
                   db[db_size].id, db[db_size].name) == 3) {
            db_size++;
        }
    }
    fclose(fp);
}

/* 从文件名中解析学号或姓名，返回学生索引 */
int search_student(const char* fragment, char type) {
    for (int i = 0; i < db_size; ++i) {
        if (type == 'i' && strstr(fragment, db[i].id)) return i;
        if (type == 'n' && strstr(fragment, db[i].name)) return i;
    }
    return -1;
}

/* 扫描并重命名 */
void scan_and_rename() {
    DIR* d = opendir(".");
    if (!d) { perror("opendir"); exit(EXIT_FAILURE); }

    struct dirent* ent;
    while ((ent = readdir(d))) {
        /* 跳过目录、“.”、“..” */
        if (ent->d_name[0] == '.') continue;

        /* 用 stat 判断普通文件 */
        struct stat st;
        if (stat(ent->d_name, &st) != 0) continue;
        if (!S_ISREG(st.st_mode)) continue;

        size_t len = strlen(ent->d_name);
        if (len < 5) continue;
        const char* ext = ent->d_name + len - 4;
        if (strcasecmp(ext, ".zip") != 0) continue;

        int idx = -1;
        if ((idx = search_student(ent->d_name, 'i')) != -1) { }
        else if ((idx = search_student(ent->d_name, 'n')) != -1) { }
        else {
            printf("未识别：%s\n", ent->d_name);
            continue;
        }

        char new_name[MAX_FILE];
        snprintf(new_name, sizeof(new_name), "%s-%s-%s.zip",
                 db[idx].class_id, db[idx].id, db[idx].name);

        if (rename(ent->d_name, new_name) == 0) {
            printf("重命名：%s -> %s\n", ent->d_name, new_name);
        } else {
            perror("rename");
        }
    }
    closedir(d);
}
int main(int argc, char* argv[]) {
    const char* db_path = (argc > 1) ? argv[1] : "data/students.txt";
    load_students(db_path);
    scan_and_rename();
    return 0;
}